package com.quanyan.travel.component.filter;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.interceptor.UserCookieFilter;
import com.quanyan.common.utils.HttpServletRequestWrapper;
import com.quanyan.common.utils.MD5Utils;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * Created by Kingson.chan on 2016/7/8 0025.
 */
@Component
public class TravelFilter extends UserCookieFilter {

    private final static Logger logger = LoggerFactory.getLogger(TravelFilter.class);

    @Autowired
    UserServiceFacade userServiceFacade;

    @Override
    protected Integer getUserIdByToken(String uMsg) {
        return userServiceFacade.getUserIdByToken(uMsg);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        long startTime = System.currentTimeMillis();
        String uri = request.getRequestURI();

        if (uri.startsWith("/admin/api/travel/") || uri.startsWith("/api/travel/callback/") || uri.startsWith("/travel/")
                || uri.startsWith("/api/travel/thymeleaf/")) {
            chain.doFilter(request, response);
            return;
        }

        String sign = request.getHeader("sign");
        ServletRequest requestWrapper = new HttpServletRequestWrapper(request);
        String reqData = getBodyString(requestWrapper.getReader(), uri);
        logger.warn("CommonFilter读取body中的参数: " + reqData);
        if (reqData == null) {
            ajaxError(ApiResponseEnum.ILLEGAL_PROTOCOL, response);
            return;
        }

        String md5Sign = MD5Utils.MD5Encode(reqData + Constants.SECRET_KEY);
        if (null==sign || !sign.equals(md5Sign)) {
            ajaxError(ApiResponseEnum.ILLEGAL_PROTOCOL, response);
            return;
        }
        logger.warn("Request End，Request URI: " + request.getRequestURI()
                + "，Time spent: " + (System.currentTimeMillis() - startTime) + "ms");
        try{
            String uMsg = request.getHeader(Constants.USER_INFORMATION_MARK);
            Integer userId = 0 ;
            userId = getUserIdByToken(uMsg);
            if(userId != null){
                request.setAttribute("uid", userId);
            }
            else {
                request.setAttribute("uid", 0);
            }
            logger.info("================= userCookiesName:{} ==> uid:{} =================", uMsg,userId);
        }catch (Exception e){
            e.printStackTrace();
        }
        chain.doFilter(requestWrapper, response);
    }

    private static String getBodyString(BufferedReader br, String reqUrl) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            logger.warn("requestUrl: " + reqUrl + ", Request error: "
                    + e.getMessage() + "Request URI: ");

        }
        return str;
    }

    private void ajaxError(ApiResponseEnum apiResponseEnum, ServletResponse response)
            throws IOException {
        response.getWriter().write(JSON.toJSON(APIResponse.returnFail(apiResponseEnum)).toString());
    }
}
